package com.czjk.controller;

import com.czjk.constant.MessageConstant;
import com.czjk.entity.Result;
import com.czjk.pojo.OrderSetting;
import com.czjk.service.OrderSettingService;
import com.czjk.util.POIUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 预约设置管理
 */
@RestController
@RequestMapping("/orderSettings")
public class OrderSettingController {

    @Autowired
    private OrderSettingService orderSettingService;

    /**
     * 下载template目录中的ordersetting_template.xlsx目标
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        //设置文件下载的头信息
        response.setHeader("Content-Disposition","attachment;filename=ordersetting_template.xlsx");
        //加载template目录中的ordersetting_template.xlsx文件
        InputStream is = this.getClass().getClassLoader().getResourceAsStream("template/ordersetting_template.xlsx");
        //响应给客户端
        IOUtils.copy(is,response.getOutputStream());
    }

    /**
     * 批量上传可预约人数
     * @param excelFile 封装了excel数据
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result upload(@RequestParam("excelFile") MultipartFile excelFile) throws IOException {
        //调用工具类方法，解析excel中的内容。excel中每行的值存到一个数组，所有行存到一个集合返回
        List<String[]> excels = POIUtils.readExcel(excelFile);
        //调用service，批量导入
        orderSettingService.importSettings(excels);
        return new Result(true, MessageConstant.IMPORT_ORDERSETTING_SUCCESS);
    }

    /**
     * 查询当月所有可预约设置
     * @param currentYear 当前年份
     * @param currentMonth 当前月份
     * @return
     */
    @GetMapping("{currentYear}/{currentMonth}")
    public Result findAll(@PathVariable String currentYear,@PathVariable String currentMonth) {
        List<Map> orderSettings = orderSettingService.findAll(currentYear, currentMonth);
        return new Result(true,MessageConstant.GET_ORDERSETTING_SUCCESS,orderSettings);
    }

    /**
     * 设置或者更新可预约人数
     * @param orderSetting 封装了日期和可预约人数
     * @return
     */
    @PutMapping
    public Result setting(@RequestBody OrderSetting orderSetting) {
        orderSettingService.setting(orderSetting);
        return new Result(true, MessageConstant.ORDERSETTING_SUCCESS);
    }
}
